import 'dart:convert';

import 'package:flame/extensions.dart';
import 'package:flutter/cupertino.dart';
import 'package:points24/domain/save_result.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../domain/express.dart';

class GameData {
  // final SharedPreferences prefs = await SharedPreferences.getInstance();

  static String dataKey = "data_key";

  static saveFailData(List<dynamic> rowNo,int time) async {
    var saveResult = SaveResult.create(rowNo, time, []);
    saveResultContent(saveResult);
  }

  ///保存成功数据
  static saveSuccessData(List<dynamic> rowNo, List<GameExpress> winSteps, int time) async {
    var saveResult = SaveResult.create(rowNo, time, winSteps);
    List<String>? datas = await saveResultContent(saveResult);
    debugPrint("------->\n${datas}");
  }

  ///保存单词数据，并返回整个数据
  static Future<List<String>?> saveResultContent(SaveResult saveResult) async {

    var outJson = saveResult.toString();
    //var saver = SaveResult.from(jsonDecode(outJson));
    //debugPrint("----->  ${saver}");

    final SharedPreferences prefs = await SharedPreferences.getInstance();
    var datas = prefs.getStringList(dataKey);
    if (null == datas) {
      var outer = <String>[];
      outer.add(outJson);
      prefs.setStringList(dataKey, outer);
    } else {
      datas.add(outJson);
      prefs.setStringList(dataKey, datas);
    }
    return datas;
  }

  ///重新保存所有
  static Future<List<String>?> reSaveAllResultContent(List<SaveResult> saveResults) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    var outer = <String>[];
    for(var saveResult in saveResults){
      var outJson = saveResult.toString();
      outer.add(outJson);
    }
    prefs.setStringList(dataKey, outer);
  }


  ///读取所有的成功和失败记录
  static Future<List<SaveResult>> readAllData() async {

    final SharedPreferences prefs = await SharedPreferences.getInstance();
    var datas = prefs.getStringList(dataKey);
    var resultList = <SaveResult>[];
    if (null != datas) {
      for (var element in datas) {
        resultList.add(SaveResult.from(jsonDecode(element)));
      }
    }
    resultList.reverse();

    return resultList;
  }
}
